package com.infore.dataReceiving.core.filter.instructions;
import java.sql.Timestamp;
import java.util.Map;

import org.springframework.util.StringUtils;
import com.infore.dataReceiving.core.chain.Water2018InstructionsChain;
import com.infore.dataReceiving.core.enums.Water2018InstructionsTypeEnum;
import com.infore.dataReceiving.core.filter.Water2018InstructionsFilter;
import com.infore.dataReceiving.dto.WaterInstructionsDto;
import com.infore.dataReceiving.entity.RealTimeData;
import com.infore.dataReceiving.repository.IBackControlLogRepository;
import com.infore.dataReceiving.util.CRCCheck;
import com.infore.dataReceiving.util.Water2018InstructionsHandleUtil;
import com.infore.dataReceiving.util.RedisUtil;

import io.netty.channel.ChannelHandlerContext;

/**
 * 实时数据
 * @author 69457
 *
 */
public class RtdFilter implements Water2018InstructionsFilter{
	
	@Override
	public void doFilter(ChannelHandlerContext ctx,WaterInstructionsDto dto,
			Water2018InstructionsChain chain,RedisUtil redisUtil,IBackControlLogRepository repository, boolean interrupt) {
		if(Water2018InstructionsTypeEnum.water2018_2011.getCn().equals(dto.getCn())) {
			interrupt = true;
			String dataTime = dto.getDataTime();
			String iflag = Integer.toBinaryString(dto.getFlag());
			String isAnswer = iflag.substring(iflag.length()-1);
//			String isPackage = iflag.substring(iflag.length()-2,iflag.length()-1);
			//有datetime，是上传实时数据，无是提取实时数据
			String mn = dto.getMn();
			Timestamp timestamp = Water2018InstructionsHandleUtil.getTimestamp(dataTime);
			if(StringUtils.isEmpty(dataTime)) {
				
			}else {
				String[] factorDatas = dto.getFactorData().split(";");
				for(String datas:factorDatas) {
					datas = ","+datas+",";
					Map<String, String> map = Water2018InstructionsHandleUtil.getInstructions_Flag(datas);
					RealTimeData realTimeData = new RealTimeData();
					realTimeData.setMn(mn);
					realTimeData.setDataTime(timestamp);
					realTimeData.setFactorCode(map.get("factorCode"));
					realTimeData.setValue(Water2018InstructionsHandleUtil.getInstructions_Rtd(datas));
					realTimeData.setFlag(map.get("flag"));
					redisUtil.lSet("realData", realTimeData);
				}
			}
			if("1".equals(isAnswer)) {
				System.out.println("正在回复实时消息！！！！！！！！！！！！！");
				String qn = dto.getQn();
				String pw = dto.getPw();
				String datas = "QN="+qn+";ST=91;CN=9014;PW="+pw+";MN="+mn+";Flag=8;CP=&&&&";
				int dataLength = datas.length();//数据段长度
				String crc = CRCCheck.crc16(datas, dataLength);
				String dataLengthString = Water2018InstructionsHandleUtil.getDataLengthString(dataLength+"");
				String returnInfo = "##"+dataLengthString+datas+crc+"\r\n";
				ctx.channel().writeAndFlush(returnInfo);
			}
		}
		chain.doFilter(ctx,dto,chain,redisUtil,repository,interrupt);
	}

}
